package ExperimentSix.ThreadPool;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest {
    public static void main(String[] args) {
        int threadCount = 5;
        ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
        final CyclicBarrier barrier = new CyclicBarrier(threadCount, () -> System.out.println("所有线程都到达了屏障，执行集体任务！"));

        for (int i = 0; i < threadCount; ++i) {
            Runnable worker = new Worker(barrier, "Worker-" + i);
            executorService.execute(worker);
        }
        executorService.shutdown();
    }

    static class Worker implements Runnable {
        private final CyclicBarrier barrier;
        private final String name;

        Worker(CyclicBarrier barrier, String name) {
            this.barrier = barrier;
            this.name = name;
        }

        public void run() {
            try {
                System.out.println(name + " 到达屏障后等待");
                barrier.await(); // 阻塞，直到所有线程到达屏障
                System.out.println(name + " 通过屏障后，一起执行同一任务");
            } catch (InterruptedException | BrokenBarrierException e) {
                Thread.currentThread().interrupt();
                e.printStackTrace();
            }
        }
    }
}